<template>
  <div class="finance-container">
    <!-- 使用导航栏组件 -->
    <NavHeader title="我的理财" @back="onClickLeft" />

    <!-- 页签导航 -->
    <div class="tabs-container">
      <van-tabs v-model:active="activeTab" @change="onTabChange" color="#1989fa" title-active-color="#1989fa">
        <van-tab title="质押" name="pledge"></van-tab>
        <van-tab title="私募" name="mining"></van-tab>
        <van-tab title="理财" name="finance"></van-tab>
      </van-tabs>
    </div>

    <!-- 项目列表 -->
    <div class="project-list">
      <div class="list-header">
        <h3>我的{{ getTabTitle() }}</h3>
      </div>

      <van-loading v-if="loading" type="spinner" color="#1989fa" vertical>
        加载中...
      </van-loading>

      <van-empty v-else-if="financeData.length === 0" description="暂无投资记录" />

      <!-- 项目卡片 -->
      <div class="project-card" v-for="(project, index) in financeData" :key="index">
        <!-- 项目头部信息 -->
        <div class="project-header" @click="toggleProjectDetail(project.name)">
          <!-- 第一行：图片 + 项目名称 + 查看详情按钮 -->
          <div class="project-top-row">
            <div class="project-left">
              <div class="project-image">
                <img :src="project.image || getDefaultIcon()" alt="项目图标">
              </div>
              <div class="project-info">
                <div class="project-name">{{ project.name }}</div>
                <div class="project-count">{{ project.count }}笔投资</div>
              </div>
            </div>
            <div class="expand-btn" :class="{ expanded: expandedProjects.includes(project.name) }">
              <span class="expand-text">查看详情</span>
              <van-icon name="arrow-down" />
            </div>
          </div>

          <!-- 第二行：总投入和总收益 -->
          <div class="project-bottom-row">
            <div class="stat-item">
              <div class="stat-value">{{ formatNumber(project.amount) }}{{ project.currency }}</div>
              <div class="stat-label">总投入</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-value profit">{{ formatNumber(project.profit) }}{{ project.incomeIcon }}</div>
              <div class="stat-label">总收益</div>
            </div>
          </div>
        </div>

        <!-- 项目详情明细（可展开） -->
        <div v-if="expandedProjects.includes(project.name)" class="project-details">
          <div class="details-header">
            <h4>参与记录</h4>
          </div>
          <div class="detail-item" v-for="(detail, detailIndex) in project.list" :key="detailIndex">
            <div class="detail-header">
              <div class="detail-left">
                <div class="detail-id">#{{ detail.id }}</div>
                <div class="detail-status" :class="getStatusClass(detail.typ)">
                  {{ getStatusText(detail.typ) }}
                </div>
              </div>
              <div class="detail-right">
                <div class="detail-amount">{{ formatNumber(detail.joinAmt) }}{{ project.currency }}</div>
              </div>
            </div>

            <div class="detail-content">
              <div class="detail-row">
                <div class="detail-info">
                  <span class="info-label">锁仓期</span>
                  <span class="info-value remaining">{{ project.lockDays }}天</span>
                </div>
                <div class="detail-info">
                  <span class="info-label">参与天数</span>
                  <span class="info-value">{{ calculateParticipationDays(detail.createdAt) }}天</span>
                </div>
              </div>

              <div class="detail-row">
                <div class="detail-info">
                  <span class="info-label">总收益</span>
                  <span class="info-value profit">{{ formatNumber(detail.totalAmt) }}</span>
                </div>
                <div class="detail-info">
                  <span class="info-label">昨日收益</span>
                  <span class="info-value profit">{{ formatNumber(detail.ysdAmt) }}</span>
                </div>
              </div>
            </div>

            <div class="detail-actions" v-if="canRedeem(detail, project.lockDays) && detail.typ === 'in'">
              <van-button type="primary" size="small" round @click="showRedeemConfirm(detail)">
                赎回
              </van-button>
            </div>
          </div>
        </div>
      </div>

    </div>

    <!-- 赎回确认对话框 -->
    <van-dialog v-model:show="redeemConfirmVisible" title="赎回确认" show-cancel-button confirm-button-text="确认赎回"
      cancel-button-text="取消" @confirm="confirmRedeem">
      <div class="redeem-confirm-content">
        <van-icon name="warning-o" class="warning-icon" />
        <p class="warning-title">您确定要赎回吗？</p>
        <p class="warning-desc">赎回后将失去后续收益。</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavHeader from '@/components/NavHeader.vue'
import { getMyFinanceList, redeemFinance } from '@/api/finance'
import { formatNumber } from '@/utils/utils'

const router = useRouter()

// 页签相关
const activeTab = ref('pledge')

// 数据相关
const financeData = ref([])
const loading = ref(false)

// 对话框控制
const redeemConfirmVisible = ref(false)
const currentRedeemItem = ref(null)

// 展开状态控制
const expandedProjects = ref([])

// 获取默认图标
const getDefaultIcon = () => {
  return new URL(`../../assets/icons/default-coin.svg`, import.meta.url).href
}

// 获取页签标题
const getTabTitle = () => {
  const titles = {
    pledge: '质押',
    mining: '私募',
    finance: '理财'
  }
  return titles[activeTab.value] || '理财'
}


// 获取状态样式类
const getStatusClass = (status) => {
  return status === 'in' ? 'status-active' : 'status-completed'
}
const getStatusText = (status) => {
  return status === 'in' ? '进行中' : '已完成'
}


// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 计算参与天数
const calculateParticipationDays = (createdAt) => {
  if (!createdAt) return 0

  try {
    // 解析创建时间 (yyyy-mm-dd HH:mm:ss)
    const createDate = new Date(createdAt)
    const currentDate = new Date()

    // 计算时间差（毫秒）
    const timeDiff = currentDate.getTime() - createDate.getTime()

    // 转换为天数
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
    return daysDiff
  } catch (error) {
    console.error('计算参与天数失败:', error)
    return 0
  }
}

// 判断是否可以赎回
const canRedeem = (item, lockDays) => {
  let days = calculateParticipationDays(item.createdAt)
  return lockDays < days
}

// 页签切换
const onTabChange = (name) => {
  activeTab.value = name
  let proType
  if (name === 'finance') {
    proType = "1" // 理财项目
  } else if (name === 'pledge') {
    proType = "2" // 质押项目
  } else if (name === 'mining') {
    proType = "3" // 私募项目
  }
  loadData(proType)
}

// 加载数据
const loadData = async (proType) => {
  try {
    loading.value = true
    const response = await getMyFinanceList({ "proType": proType })

    if (response.code === 0 && response.data) {
      // 将API返回的FinanceCardResp数组赋值给financeData
      financeData.value = response.data.map(card => ({
        ...card,
        // 确保数据格式正确
        amount: parseFloat(card.amount) || 0,
        profit: parseFloat(card.profit) || 0,
        image: card.image || getDefaultIcon(),
        currency: card.currency || 'USDT',
        incomeIcon: card.incomeIcon || card.currency || 'USDT',
        count: card.count || 0,
        list: card.list || [],
        proType: parseInt(card.proType) || 1 // 确保proType为数字类型
      }))
    } else {
      console.error('获取理财数据失败:', response.message)
      showToast({
        type: 'fail',
        message: response.message || '获取数据失败'
      })
    }
  } catch (error) {
    console.error('加载理财数据失败:', error)
    showToast({
      type: 'fail',
      message: '网络错误，请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

// 显示赎回确认对话框
const showRedeemConfirm = (item) => {
  currentRedeemItem.value = item
  redeemConfirmVisible.value = true
}

// 确认赎回
const confirmRedeem = async () => {
  if (!currentRedeemItem.value) return

  try {
    const response = await redeemFinance({ recId: currentRedeemItem.value.id })

    if (response.code === 0) {
      // 重新加载数据
      let proType
      if (activeTab.value === 'finance') {
        proType = "1"
      } else if (activeTab.value === 'pledge') {
        proType = "2"
      } else if (activeTab.value === 'mining') {
        proType = "3"
      }
      await loadData(proType)
    } else {
      showToast({
        type: 'fail',
        message: response.message || '赎回失败，请稍后再试'
      })
    }
  } catch (error) {
    console.error('赎回失败:', error)
    showToast({
      type: 'fail',
      message: '网络错误，请稍后再试'
    })
  } finally {
    redeemConfirmVisible.value = false
    currentRedeemItem.value = null
  }
}

// 切换项目详情展开状态
const toggleProjectDetail = (projectName) => {
  const index = expandedProjects.value.indexOf(projectName)
  if (index > -1) {
    expandedProjects.value.splice(index, 1)
  } else {
    expandedProjects.value.push(projectName)
  }
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 页面加载时获取数据
onMounted(() => {
  // 默认加载质押数据（第一个页签）
  loadData("2")
})
</script>

<style lang="scss" scoped>
.finance-container {
  background: linear-gradient(135deg, #1989fa 0%, #4fc3f7 100%);
  min-height: 100vh;
  padding-top: 54px;

  // 页签容器
  .tabs-container {
    background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
    margin: 0 20px 24px;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.8);

    :deep(.van-tabs__wrap) {
      background: transparent;
      padding: 8px;
    }

    :deep(.van-tabs__nav) {
      background: transparent;
      border-radius: 16px;
    }

    :deep(.van-tab) {
      font-weight: 600;
      font-size: 16px;
      color: #64748b;
      padding: 16px 24px;
      transition: all 0.3s ease;

      &.van-tab--active {
        color: #1989fa;
        font-weight: 700;
      }
    }

    :deep(.van-tabs__line) {
      background: linear-gradient(135deg, #1989fa 0%, #4fc3f7 100%);
      height: 4px;
      border-radius: 2px;
      box-shadow: 0 2px 8px rgba(25, 137, 250, 0.3);
    }
  }

  // 统计卡片
  .stats-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    margin: 0 16px 20px;
    border-radius: 20px;
    padding: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);

    .stats-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .stats-title {
        font-size: 18px;
        font-weight: 600;
        color: #2d3748;
      }

      .stats-refresh {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: linear-gradient(135deg, #1989fa 0%, #4fc3f7 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          transform: rotate(180deg);
          box-shadow: 0 4px 15px rgba(25, 137, 250, 0.4);
        }

        .van-icon {
          color: white;
          font-size: 18px;
        }
      }
    }

    .stats-content {
      display: flex;
      align-items: center;

      .stat-item {
        flex: 1;
        text-align: center;

        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #2d3748;
          margin-bottom: 8px;

          &.profit {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }
        }

        .stat-label {
          font-size: 14px;
          color: #718096;
          font-weight: 500;
        }
      }

      .stat-divider {
        width: 1px;
        height: 40px;
        background: linear-gradient(to bottom, transparent, #e2e8f0, transparent);
        margin: 0 20px;
      }
    }
  }

  // 项目列表
  .project-list {
    padding: 0 16px 40px;

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      h3 {
        font-size: 22px;
        font-weight: 700;
        color: white;
        margin: 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

    }

    // 项目卡片
    .project-card {
      background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
      border-radius: 20px;
      margin-bottom: 20px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
      border: 1px solid rgba(255, 255, 255, 0.8);
      overflow: hidden;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      backdrop-filter: blur(20px);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
        border-color: rgba(25, 137, 250, 0.2);
      }

      // 项目头部
      .project-header {
        padding: 24px 20px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background: linear-gradient(135deg, rgba(25, 137, 250, 0.02) 0%, rgba(79, 195, 247, 0.02) 100%);
        }

        // 第一行：图片 + 项目名称 + 查看详情按钮
        .project-top-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .project-left {
            display: flex;
            align-items: center;
            flex: 1;

            .project-image {
              width: 56px;
              height: 56px;
              border-radius: 16px;
              overflow: hidden;
              margin-right: 16px;
              background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
              box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
              position: relative;
              flex-shrink: 0;

              &::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(135deg, rgba(25, 137, 250, 0.1) 0%, rgba(79, 195, 247, 0.1) 100%);
                opacity: 0;
                transition: opacity 0.3s ease;
              }

              &:hover::before {
                opacity: 1;
              }

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                transition: transform 0.3s ease;
              }

              &:hover img {
                transform: scale(1.05);
              }
            }

            .project-info {
              flex: 1;
              min-width: 0;

              .project-name {
                font-size: 18px;
                font-weight: 700;
                color: #1a202c;
                margin-bottom: 6px;
                line-height: 1.3;
                letter-spacing: -0.3px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }

              .project-count {
                font-size: 13px;
                color: #64748b;
                background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
                padding: 4px 12px;
                border-radius: 12px;
                display: inline-block;
                font-weight: 500;
                border: 1px solid rgba(148, 163, 184, 0.1);
              }
            }
          }

          .expand-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 10px 16px;
            border-radius: 20px;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid rgba(148, 163, 184, 0.1);
            flex-shrink: 0;

            .expand-text {
              font-size: 13px;
              color: #64748b;
              font-weight: 600;
              letter-spacing: 0.3px;
            }

            .van-icon {
              font-size: 14px;
              color: #64748b;
              transition: transform 0.3s ease;
            }

            &.expanded {
              background: linear-gradient(135deg, #1989fa 0%, #4fc3f7 100%);
              border-color: rgba(25, 137, 250, 0.3);
              box-shadow: 0 2px 8px rgba(25, 137, 250, 0.2);

              .expand-text {
                color: white;
              }

              .van-icon {
                color: white;
                transform: rotate(180deg);
              }
            }

            &:hover:not(.expanded) {
              background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e0 100%);
              transform: translateY(-1px);
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
            }
          }
        }

        // 第二行：总投入和总收益
        .project-bottom-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
          background: linear-gradient(135deg, rgba(248, 250, 252, 0.8) 0%, rgba(241, 245, 249, 0.8) 100%);
          border-radius: 16px;
          border: 1px solid rgba(226, 232, 240, 0.5);

          .stat-item {
            flex: 1;
            text-align: center;

            .stat-value {
              font-size: 16px;
              font-weight: 700;
              color: #1a202c;
              margin-bottom: 4px;
              line-height: 1.2;

              &.profit {
                background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
              }
            }

            .stat-label {
              font-size: 12px;
              color: #64748b;
              font-weight: 500;
              letter-spacing: 0.3px;
            }
          }

          .stat-divider {
            width: 1px;
            height: 32px;
            background: linear-gradient(to bottom, transparent, #e2e8f0, transparent);
            margin: 0 16px;
          }
        }
      }

      // 项目详情明细
      .project-details {
        border-top: 1px solid #f1f5f9;
        background: linear-gradient(135deg, #fafbfc 0%, #f1f5f9 100%);

        .details-header {
          padding: 24px 28px 16px;

          h4 {
            font-size: 18px;
            font-weight: 700;
            color: #1a202c;
            margin: 0;
            letter-spacing: -0.3px;
          }
        }

        .detail-item {
          padding: 20px 28px;
          border-bottom: 1px solid rgba(226, 232, 240, 0.6);
          transition: all 0.3s ease;

          &:last-child {
            border-bottom: none;
            padding-bottom: 28px;
          }

          &:hover {
            background: linear-gradient(135deg, rgba(248, 250, 252, 0.8) 0%, rgba(241, 245, 249, 0.8) 100%);
          }

          .detail-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;

            .detail-left {
              display: flex;
              align-items: center;
              gap: 16px;

              .detail-id {
                font-size: 13px;
                color: #64748b;
                background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
                padding: 4px 12px;
                border-radius: 12px;
                font-weight: 600;
                border: 1px solid rgba(148, 163, 184, 0.1);
              }

              .detail-status {
                padding: 6px 14px;
                border-radius: 14px;
                font-size: 12px;
                font-weight: 600;
                letter-spacing: 0.3px;

                &.status-active {
                  background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
                  color: #166534;
                  border: 1px solid rgba(34, 197, 94, 0.2);
                }

                &.status-completed {
                  background: linear-gradient(135deg, #fecaca 0%, #fca5a5 100%);
                  color: #dc2626;
                  border: 1px solid rgba(239, 68, 68, 0.2);
                }
              }
            }

            .detail-right {
              .detail-amount {
                font-size: 18px;
                font-weight: 700;
                color: #1a202c;
                letter-spacing: -0.3px;
              }
            }
          }

          .detail-content {
            .detail-row {
              display: flex;
              justify-content: space-between;
              margin-bottom: 16px;

              &:last-child {
                margin-bottom: 0;
              }

              .detail-info {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;
                text-align: center;
                padding: 16px 8px;
                background: linear-gradient(135deg, rgba(248, 250, 252, 0.8) 0%, rgba(255, 255, 255, 0.8) 100%);
                border-radius: 16px;
                margin: 0 6px;
                border: 1px solid rgba(226, 232, 240, 0.5);
                transition: all 0.3s ease;

                &:hover {
                  transform: translateY(-2px);
                  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
                  border-color: rgba(25, 137, 250, 0.2);
                }

                .info-label {
                  font-size: 12px;
                  color: #64748b;
                  margin-bottom: 8px;
                  font-weight: 500;
                  letter-spacing: 0.3px;
                }

                .info-value {
                  font-size: 15px;
                  font-weight: 700;
                  color: #1a202c;
                  letter-spacing: -0.2px;

                  &.profit {
                    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                    background-clip: text;
                  }

                  &.remaining {
                    color: #dc2626;
                  }
                }
              }
            }
          }

          .detail-actions {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid rgba(226, 232, 240, 0.6);
            display: flex;
            justify-content: flex-end;

            .van-button {
              background: linear-gradient(135deg, #1989fa 0%, #4fc3f7 100%);
              border: none;
              box-shadow: 0 4px 16px rgba(25, 137, 250, 0.3);
              font-size: 14px;
              height: 40px;
              padding: 0 24px;
              font-weight: 600;
              letter-spacing: 0.3px;

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 24px rgba(25, 137, 250, 0.4);
              }
            }
          }
        }
      }
    }
  }

  // 赎回确认对话框
  .redeem-confirm-content {
    padding: 20px;
    text-align: center;

    .warning-icon {
      font-size: 48px;
      color: #f56565;
      margin-bottom: 16px;
    }

    .warning-title {
      font-size: 18px;
      font-weight: 600;
      color: #2d3748;
      margin-bottom: 8px;
    }

    .warning-desc {
      font-size: 14px;
      color: #718096;
      margin-bottom: 20px;
    }

    .redeem-info {
      background: #f7fafc;
      border-radius: 12px;
      padding: 16px;

      .redeem-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .amount {
          font-weight: 600;
          color: #2d3748;
        }

        .profit {
          font-weight: 600;
          color: #10b981;
        }
      }
    }
  }
}
</style>